package service

import (
	"context"
	"fx_swift_boss/api"
	"fx_swift_boss/internal/model"
	"fx_swift_boss/pkg/code"
	"fx_swift_boss/pkg/global"
	"fx_swift_boss/pkg/internalerrors"
	"fx_swift_boss/pkg/logger"
	"fx_swift_boss/pkg/page"
	"github.com/spf13/cast"
)

// boss端公告
type IPlacardSrv interface {
	AddPlacard(ctx context.Context, req *api.AddPlacardReq) error

	GetPlacard(ctx context.Context, req *api.GetPlacardReq) (*page.Collection[*api.GetPlacardRes], error)

	DelPlacard(ctx context.Context, id string) error
}

type placard struct {
}

func NewPlacardSrv() IPlacardSrv {
	return &placard{}
}

func (p *placard) AddPlacard(ctx context.Context, req *api.AddPlacardReq) error {
	var (
		err error
	)
	if req.Type == "ifcgate" {
		global.GFDB.Ctx(ctx).Schema("boss").Model("fx_placard").Update("flag='0' and type='ifcgate'")
	} else if req.Type == "ifcgate_agent" {
		global.GFDB.Ctx(ctx).Schema("boss").Model("fx_placard").Update("flag='0' and type='ifcgate_agent'")
	}
	if _, err = global.GFDB.Ctx(ctx).Schema("boss").Model("fx_placard").Insert(&model.FxPlacard{
		Type:    req.Type,
		Content: req.Content,
		Flag:    "1",
	}); err != nil {
		logger.SugarLogger.Error(err.Error())
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	return err
}

func (p *placard) GetPlacard(ctx context.Context, req *api.GetPlacardReq) (*page.Collection[*api.GetPlacardRes], error) {
	var (
		err   error
		total int
		list  []*api.GetPlacardRes
	)
	collectionDto := &page.Collection[*api.GetPlacardRes]{}
	collectionDto.Page = req.PageNo
	collectionDto.PageSize = req.PageSize
	mod := global.GFDB.Ctx(ctx).Schema("boss").Model("fx_placard").
		Order("created_at desc")
	mod.Limit(int(page.PageToOffset(req.PageNo, req.PageSize)), cast.ToInt(req.PageSize))
	err = mod.ScanAndCount(&list, &total, false)
	collectionDto.TotalPage = page.GetTotalPage(req.PageNo, req.PageSize, cast.ToInt64(total))
	if err != nil {
		logger.SugarLogger.Error(err.Error())
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}
	collectionDto.Total = cast.ToInt64(total)
	collectionDto.List = list
	return collectionDto, err
}

func (p *placard) DelPlacard(ctx context.Context, id string) error {
	var (
		err error
	)
	if _, err = global.GFDB.Ctx(ctx).Schema("boss").Model("fx_placard").Delete("id=?", id); err != nil {
		logger.SugarLogger.Error(err.Error())
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	return err
}
